package GUI;

import CDB.PersonFactory;
import CDB.Producto;
import Negocios.ControlProduct;
import java.beans.PropertyVetoException;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author ISC Erick Lopez Martinez
 */
public class PuntoVenta extends javax.swing.JInternalFrame {

    /**
     * Creates new form PuntoVenta
     */
    public PuntoVenta() {
        initComponents();
        start();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlControls = new javax.swing.JPanel();
        txtCodBar = new javax.swing.JTextField();
        btnBorrar = new javax.swing.JButton();
        btnVender = new javax.swing.JButton();
        btnCerrar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        txtTotal = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblVenta = new javax.swing.JTable();

        setBackground(new java.awt.Color(255, 255, 255));
        setClosable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Sales Tea Dispatcher - Punto de Venta");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/dollar.png"))); // NOI18N
        setMinimumSize(new java.awt.Dimension(768, 768));

        pnlControls.setBackground(new java.awt.Color(204, 204, 204));
        pnlControls.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        pnlControls.setRequestFocusEnabled(false);

        txtCodBar.setBackground(new java.awt.Color(204, 204, 204));
        txtCodBar.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        txtCodBar.setForeground(new java.awt.Color(0, 51, 255));
        txtCodBar.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtCodBar.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 204), 2, true), "Codigo de barras", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 0, 18), new java.awt.Color(0, 51, 204))); // NOI18N
        txtCodBar.setFocusCycleRoot(true);
        txtCodBar.setOpaque(false);
        txtCodBar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCodBarActionPerformed(evt);
            }
        });
        txtCodBar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCodBarKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtCodBarKeyTyped(evt);
            }
        });

        btnBorrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/delete.png"))); // NOI18N
        btnBorrar.setText("Borrar");
        btnBorrar.setRequestFocusEnabled(false);
        btnBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBorrarActionPerformed(evt);
            }
        });

        btnVender.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/dollar.png"))); // NOI18N
        btnVender.setText("Vender");
        btnVender.setRequestFocusEnabled(false);
        btnVender.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVenderActionPerformed(evt);
            }
        });

        btnCerrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/Cancel.png"))); // NOI18N
        btnCerrar.setText("Cerrar");
        btnCerrar.setRequestFocusEnabled(false);
        btnCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCerrarActionPerformed(evt);
            }
        });

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IconosGenerales/shopcart.png"))); // NOI18N
        jLabel1.setRequestFocusEnabled(false);

        txtTotal.setBackground(new java.awt.Color(204, 204, 204));
        txtTotal.setFont(new java.awt.Font("Arial", 1, 36)); // NOI18N
        txtTotal.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtTotal.setText("$0.0");
        txtTotal.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 204, 0), 2, true), "TOTAL", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 0, 18), new java.awt.Color(0, 204, 0))); // NOI18N
        txtTotal.setOpaque(false);
        txtTotal.setRequestFocusEnabled(false);
        txtTotal.setSelectionColor(new java.awt.Color(0, 255, 0));
        txtTotal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtTotalActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlControlsLayout = new javax.swing.GroupLayout(pnlControls);
        pnlControls.setLayout(pnlControlsLayout);
        pnlControlsLayout.setHorizontalGroup(
            pnlControlsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlControlsLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlControlsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(txtCodBar, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnCerrar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnBorrar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnVender, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
            .addGroup(pnlControlsLayout.createSequentialGroup()
                .addGap(41, 41, 41)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        pnlControlsLayout.setVerticalGroup(
            pnlControlsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlControlsLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtCodBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnVender, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnBorrar, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCerrar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pnlControlsLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnBorrar, btnCerrar, btnVender});

        jScrollPane2.setRequestFocusEnabled(false);

        tblVenta.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        tblVenta.setFont(new java.awt.Font("Arial", 0, 24)); // NOI18N
        tblVenta.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nombre del producto.", "Precio"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblVenta.setToolTipText("Productos en venta actualmente");
        tblVenta.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        tblVenta.setGridColor(new java.awt.Color(255, 255, 255));
        tblVenta.setRequestFocusEnabled(false);
        tblVenta.setSelectionBackground(new java.awt.Color(255, 106, 0));
        tblVenta.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tblVenta.addContainerListener(new java.awt.event.ContainerAdapter() {
            public void componentAdded(java.awt.event.ContainerEvent evt) {
                tblVentaComponentAdded(evt);
            }
        });
        jScrollPane2.setViewportView(tblVenta);
        tblVenta.getColumnModel().getColumn(0).setResizable(false);
        tblVenta.getColumnModel().getColumn(0).setPreferredWidth(80);
        tblVenta.getColumnModel().getColumn(1).setResizable(false);
        tblVenta.getColumnModel().getColumn(1).setPreferredWidth(10);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 779, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlControls, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 627, Short.MAX_VALUE)
                    .addComponent(pnlControls, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        getAccessibleContext().setAccessibleDescription("");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtTotalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtTotalActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtTotalActionPerformed

    private void btnCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCerrarActionPerformed
        try {
            this.setClosed(true);
            System.gc();
        } catch (PropertyVetoException ex) {
            this.dispose();
            System.gc();
        }
    }//GEN-LAST:event_btnCerrarActionPerformed

    private void btnVenderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVenderActionPerformed

        if (tblVenta.getRowCount() > 0) {
            DefaultTableModel model;
            model = (DefaultTableModel) tblVenta.getModel();
            for (int i = tblVenta.getRowCount() - 1; i > -1; i--) {
                model.removeRow(i);
            }
            txtTotal.setText("$0.0");
            JOptionPane.showMessageDialog(rootPane, "Venta realizada.", "Vendido con exito", 1);
        } else {
            JOptionPane.showMessageDialog(rootPane, "No puede hacer una venta sin "
                    + "ningun producto.", "Venta sin productos.", 0);
        }

        txtCodBar.requestFocus();
    }//GEN-LAST:event_btnVenderActionPerformed

    private void tblVentaComponentAdded(java.awt.event.ContainerEvent evt) {//GEN-FIRST:event_tblVentaComponentAdded
    }//GEN-LAST:event_tblVentaComponentAdded

    private void txtCodBarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCodBarActionPerformed
        if (txtCodBar.getText().equals("") == false) {
            DefaultTableModel model = (DefaultTableModel) tblVenta.getModel();
            ControlProduct cp = new ControlProduct();

//            try {
//                Producto product = cp.selectOne(Integer.parseInt(txtCodBar.getText()));
//                if (product.size() > 0) {
//                    for (int i = 0; i < product.size(); i++) {
//                        Producto p = (Producto) product.get(i);
//                        //model.addRow(new String[]{p.getNombre(), "$"+String.valueOf(p.getCosto())});
//
//                        txtTotal.setText("$"
//                                + (Float.parseFloat(model.getValueAt(tblVenta.getRowCount()-1, 1).toString().substring(1))
//                                + Float.parseFloat(txtTotal.getText().substring(1))));
//                    }
//                } else {
//                    JOptionPane.showMessageDialog(this, "El producto"
//                            + " con el codigo de barras: " + txtCodBar.getText()
//                            + ", no esta registrado.", "Error", 0);
//                    txtCodBar.setText("");
//                }
//            } catch (Exception e) {
//                txtCodBar.setText("");
//                JOptionPane.showMessageDialog(this, e, "Error", 0);
//            }
//
//        } else {
//            JOptionPane.showMessageDialog(this, "Por favor introduca un codigo "
//                    + "de barras", "Codigo de barras vacio", 0);
        }

        txtCodBar.setText("");
    }//GEN-LAST:event_txtCodBarActionPerformed

    private void btnBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBorrarActionPerformed

        if (tblVenta.getSelectedRow() > -1) {
            DefaultTableModel model = (DefaultTableModel) tblVenta.getModel();
            model.removeRow(tblVenta.getSelectedRow());
            txtTotal.setText("$0.0");
            for (int i = tblVenta.getRowCount() - 1; i > -1; i--) {
                txtTotal.setText("$"
                        + (Float.parseFloat(model.getValueAt(i, 1).toString().substring(1))
                        + Float.parseFloat(txtTotal.getText().substring(1))));
            }
        } else {
            JOptionPane.showMessageDialog(this, "Seleccione un producto de la "
                    + "tabla para poder borrarlo.", "Producto no seleccionado", 0);
        }
        txtCodBar.requestFocus();
    }//GEN-LAST:event_btnBorrarActionPerformed

    private void txtCodBarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodBarKeyPressed
    }//GEN-LAST:event_txtCodBarKeyPressed

    private void txtCodBarKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodBarKeyTyped
        char key = evt.getKeyChar();
        if ((key < '0' || key > '9') && (key != '\b') && (key != '\n')) {
            evt.consume();
            JOptionPane.showMessageDialog(this, "Solo se permiten numeros en "
                    + "este campo", "Lestras no permitidas", 0);
        }
    }//GEN-LAST:event_txtCodBarKeyTyped

    private void start() {
        TableColumn column = tblVenta.getColumn("Precio");
        column.setMinWidth(125);
        column.setMaxWidth(125);
        tblVenta.setRowHeight(30);
        txtCodBar.requestFocusInWindow();
    }

    public Session createSession() {

        Session session = null;
        try {
            //creando la nueva session para usar hibernate
            SessionFactory sessionFactory = PersonFactory.getSessionFactory();
            session = sessionFactory.openSession();

        } catch (HibernateException e) {
            JOptionPane.showMessageDialog(null, e);
            session.close();
        }
        return session;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBorrar;
    private javax.swing.JButton btnCerrar;
    private javax.swing.JButton btnVender;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPanel pnlControls;
    private javax.swing.JTable tblVenta;
    private javax.swing.JTextField txtCodBar;
    private javax.swing.JTextField txtTotal;
    // End of variables declaration//GEN-END:variables
}
